package com.ruoyi.student.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.github.pagehelper.Page;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.student.domain.StudentYfydDto;
import com.ruoyi.student.listener.YfydListener;
import com.ruoyi.student.runnables.ExcelInsertRunnable;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.student.mapper.StudentYfydMapper;
import com.ruoyi.student.domain.StudentYfyd;
import com.ruoyi.student.service.IStudentYfydService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 学生一分一段Service业务层处理
 *
 * @author zyf
 * @date 2024-09-03
 */
@Service
public class StudentYfydServiceImpl implements IStudentYfydService {
    @Autowired
    private StudentYfydMapper studentYfydMapper;

    /**
     * 查询学生一分一段
     *
     * @param id 学生一分一段主键
     * @return 学生一分一段
     */
    @Override
    public StudentYfyd selectStudentYfydById(Long id) {
        return studentYfydMapper.selectStudentYfydById(id);
    }

    /**
     * 查询学生一分一段列表
     *
     * @param studentYfyd 学生一分一段
     * @return 学生一分一段
     */
    @Override
    public List<StudentYfyd> selectStudentYfydList(StudentYfyd studentYfyd) {
        return studentYfydMapper.selectStudentYfydList(studentYfyd);
    }

    /**
     * 查询学生一分一段列表
     *
     * @param studentYfyd 学生一分一段
     * @return 学生一分一段
     */
    @Override
    public List<StudentYfyd> selectStudentYfydLists(StudentYfyd studentYfyd, List<StudentYfyd> list) {
        list = getResult(list, studentYfyd.getScore(), "score");
        list = getResult(list, studentYfyd.getPlace(), "place");
        List<Long> collect = list.stream().map(StudentYfyd::getId).collect(Collectors.toList());
        return studentYfydMapper.selectStudentYfydByIds(collect);
    }

    /**
     * 查询学生一分一段列表（缺少部分查询参数时score、place）
     *
     * @param studentYfyd 学生一分一段
     * @return 学生一分一段
     */
    @Override
    public List<StudentYfyd> selectStudentYfydLists(StudentYfyd studentYfyd) {
        //        list = getResult(list, studentYfyd.getScore(), "score");
        //        list = getResult(list, studentYfyd.getPlace(), "place");
        return studentYfydMapper.selectStudentYfydList(studentYfyd);
    }

    /**
     * 查询学生一分一段列表不分页
     *
     * @param studentYfyd 学生一分一段
     * @return 学生一分一段
     */

    @Override
    public List<StudentYfyd> selectStudentYfydListNoPage(StudentYfyd studentYfyd) {
        return studentYfydMapper.selectStudentYfydLists(studentYfyd);
    }

    //        提取数据
    public <T> List<T> getResult(List<T> result, String keys, String filed) {
        if (result.size() != 0) {
            if (StringUtils.isNotEmpty(keys)) {
                result = result.stream().filter(e -> {
                    String msg = null;
                    try {
                        Field field = e.getClass().getDeclaredField(filed);
                        field.setAccessible(true); // 设置私有字段可访问
                        msg = (String) field.get(e);
                    } catch (IllegalAccessException | NoSuchFieldException illegalAccessException) {
                        throw new RuntimeException("没有该字段");
                    }
                    if (!StringUtils.isNotEmpty(msg)) {
                        throw new RuntimeException("没有该字段");
                    }
                    if (msg.equals(keys)) {
                        return true;
                    }
                    if (msg.contains("~")) {
                        String[] split = msg.split(" ~ ");
                        return Integer.parseInt(split[0]) <= Integer.parseInt(keys) &&
                                Integer.parseInt(split[1]) >= Integer.parseInt(keys);
                    }
                    return false;
                }).collect(Collectors.toList());
            }
        }
        return result;
    }

    /**
     * 新增学生一分一段
     *
     * @param studentYfyd 学生一分一段
     * @return 结果
     */
    @Override
    public int insertStudentYfyd(StudentYfyd studentYfyd) {
        return studentYfydMapper.insertStudentYfyd(studentYfyd);
    }

    /**
     * 修改学生一分一段
     *
     * @param studentYfyd 学生一分一段
     * @return 结果
     */
    @Override
    public int updateStudentYfyd(StudentYfyd studentYfyd) {
        return studentYfydMapper.updateStudentYfyd(studentYfyd);
    }

    /**
     * 批量删除学生一分一段
     *
     * @param ids 需要删除的学生一分一段主键
     * @return 结果
     */
    @Override
    public int deleteStudentYfydByIds(Long[] ids) {
        return studentYfydMapper.deleteStudentYfydByIds(ids);
    }

    /**
     * 删除学生一分一段信息
     *
     * @param id 学生一分一段主键
     * @return 结果
     */
    @Override
    public int deleteStudentYfydById(Long id) {
        return studentYfydMapper.deleteStudentYfydById(id);
    }

    /**
     * 导入excel
     *
     * @param files 学生一分一段excel录入信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addExcel(List<MultipartFile> files) throws IOException {
        //开启线程池执
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
        for (MultipartFile file : files) {
            HashMap<String, String> excelMsg = getExcelMsg(Objects.requireNonNull(file.getOriginalFilename()));
            List<StudentYfyd> list = new ArrayList<>();
            InputStream inputStream = file.getInputStream();
            YfydListener yfydListener = new YfydListener(excelMsg, list);
            EasyExcel.read(inputStream, StudentYfydDto.class, yfydListener).headRowNumber(0)
                    .build().readAll();
            //            开启线程插入数据
            scheduledExecutorService.execute(new ExcelInsertRunnable(list, studentYfydMapper));
        }
//        关闭线程池
        scheduledExecutorService.shutdown();
    }

    //    根据文件名获得省份与年份
    public HashMap<String, String> getExcelMsg(String fileName) {
        // 解析省份,从第二个字符开始，直到"】"
        String prefix = fileName.substring(1, fileName.indexOf("】"));

        // 解析年份
        String year = fileName.substring(fileName.indexOf("】") + 1, fileName.indexOf("一分一段表"));

        HashMap<String, String> stringStringHashMap = new HashMap<>();
        stringStringHashMap.put("省份", prefix);
        stringStringHashMap.put("年份", year);
        return stringStringHashMap;
    }
}
